#!/usr/bin/env python
# -*- coding:utf8 -*-
"""
Author : mafei
Date   : 2019-12-07
"""
import uuid
import coreapi
import coreschema
from mmonitor.models.mysql_db import UserModel, WebSiteModel, HistoryModel, ErrorHistoryModel, AlertStatusModel
from .base import ViewBase
from mmonitor.utils.validator import is_uuid4
from mmonitor.common.vars import attack_msg
from peewee import IntegrityError
from mmonitor.common.rpc_func import RpcClient


class WebSiteView(ViewBase):

    _rpc_client = None


    get_fields = (
        coreapi.Field(
            name='url_id',
            location='query',
            description=u'web url_id',
            required=True,
            type="String",
            schema=coreschema.String()
        ),
    )

    put_fields = (
        coreapi.Field(
            name='u_id',
            location='query',
            description=u'用户id',
            required=True,
            type="String",
            example="example",
            schema=coreschema.String()
        ),
        coreapi.Field(
            name='url',
            location='query',
            description=u'url',
            required=True,
            type="String",
            example="example",
            schema=coreschema.String()
        ),
        coreapi.Field(
            name='name',
            location='query',
            description=u'监控名称',
            required=True,
            type="String",
            example="example",
            schema=coreschema.String()
        ),
        coreapi.Field(
            name='interval',
            location='query',
            description=u'监控间隔',
            required=True,
            type="Integer",
            example="example",
            schema=coreschema.String()
        ),
    )

    post_fields = (
        coreapi.Field(
            name='url_id',
            location='query',
            description=u'url_id',
            required=True,
            type="String",
            schema=coreschema.String()
        ),
        coreapi.Field(
            name='u_id',
            location='query',
            description=u'用户id',
            required=True,
            type="String",
            schema=coreschema.String()
        ),
        coreapi.Field(
            name='url',
            location='query',
            description=u'url',
            required=True,
            type="String",
            schema=coreschema.String()
        ),
        coreapi.Field(
            name='name',
            location='query',
            description=u'监控名称',
            required=True,
            type="String",
            schema=coreschema.String()
        ),
        coreapi.Field(
            name='interval',
            location='query',
            description=u'监控间隔',
            required=True,
            type="Integer",
            schema=coreschema.String()
        )
    )

    @property
    def rpc_client(self):
        if self._rpc_client is None:
            self._rpc_client = RpcClient()
        return self._rpc_client

    def get(self, request):
        user_id = request.session["user"]
        if not is_uuid4(user_id):
            return self.error_response(attack_msg)
        user = UserModel.get_or_none(UserModel.user_id == user_id)
        if not user:
            return self.error_response("用户丢了")
        url_id = request.qget_string("url_id", "")
        if url_id:
            print("获取到的url_id:{}".format(url_id))
            url = WebSiteModel.get_or_none((WebSiteModel.url_id == url_id))
            if not url:
                return self.error_response("url不存在!")
            url.interval = url.interval / 60
            return self.ok_response(url.to_dict())
        url_data = WebSiteModel.select().where(WebSiteModel.user_id == user.id)
        if not url_data:
            return self.ok_response(data=[], msg="还没有监控项")
        # url_data = url_data.to_dict()
        # url_data.pop("id")
        # url_data.pop("job_id")
        result = []
        for u in url_data:
            u.interval = u.interval / 60
            u = u.to_dict()
            u.pop("id")
            u.pop("job_id")
            result.append(u)

        return self.ok_response(result)

    def post(self, request):
        url_id = request.bget_string("url_id")
        user_id = request.session['user']
        monitor_name = request.bget_string("name")
        interval = request.bget_int("interval")* 60
        is_enable = request.bget_string("is_enable", 0)
        if is_enable:
            is_enable = 1
        if not is_uuid4(user_id) or not is_uuid4(url_id):
            return self.error_response(attack_msg)
        user = UserModel.get_or_none(UserModel.user_id == user_id)
        if not user:
            return self.error_response("用户丢了")

        url_data = WebSiteModel.get_or_none(WebSiteModel.url_id == url_id)
        if not url_data:
            return self.error_response("你要找的监控项不存在")
        url_data.name = monitor_name
        url_data.interval = interval
        if url_data.is_enable != is_enable:
            if is_enable:
                self.rpc_client.resume_job(url_data.job_id)
            else:
                self.rpc_client.pause_job(url_data.job_id)
        url_data.is_enable = is_enable
        d = {
            "name": monitor_name,
            "interval": interval,
            "is_enable": is_enable
        }
        try:
            WebSiteModel.update(**d).where(WebSiteModel.url_id == url_id).execute()
        except IntegrityError:
            return self.logic_error_response("url已经添加过了。")
        return self.ok_response(url_data.to_dict())

    def put(self, request):
        # 预警的设置后边再做
        user_id = request.session['user']
        url = request.bget_string("url")
        monitor_name = request.bget_string("name")
        interval = request.bget_int("interval") * 60
        is_enable = request.bget_string("is_enable", 0)
        if is_enable:
            is_enable = 1
        if not is_uuid4(user_id):
            return self.error_response(attack_msg)
        user = UserModel.get_or_none(UserModel.user_id == user_id)
        if not user:
            return self.error_response("用户丢了")

        d = {
            "user_id": user.id,
            "url": url,
            "name": monitor_name,
            "interval": interval,
            "is_enable": is_enable
        }
        if WebSiteModel.get_or_none(**{"user_id": user.id, "url": url}):
            return self.logic_error_response("url已经添加过了。")
        res = WebSiteModel.create(**d)

        res.job_id = self.rpc_client.add_job(res.id, interval).id
        if not is_enable:
            self.rpc_client.pause_job(res.job_id)
        else:
            self.logger.info("start add job url_id:{}  interval:{}".format(res.id, interval))
        res.save()

        return self.ok_response(data={"url_id": res.url_id})

    def delete(self, request):
        url_id = request.bget_string("url_id")
        if not is_uuid4(url_id):
            return self.error_response(attack_msg)

        url_data = WebSiteModel.get_or_none(WebSiteModel.url_id == url_id)
        if not url_data:
            return self.error_response("你要找的监控项不存在")
        self.rpc_client.remove_job(url_data.job_id)
        self.logger.info("start delete history by item_id :{}".format(url_data.id))
        HistoryModel.delete().where(HistoryModel.item_id == url_data.id).execute()
        ErrorHistoryModel.delete().where(ErrorHistoryModel.item_id == url_data.id).execute()
        AlertStatusModel.delete().where(AlertStatusModel.item_id == url_data.id).execute()
        self.logger.info("start delete WebSiteModel by id :{}".format(url_data.id))

        WebSiteModel.delete().where(WebSiteModel.id == url_data.id).execute()
        return self.ok_response()
